package dao;

import java.util.List;

import model.Company;
import model.Product;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import util.HibernateUtil;

public class companyDAO {
	private Session session;
	public companyDAO() {
		this.session = HibernateUtil.getSessionFactory().openSession();
	}
	@SuppressWarnings("unchecked")
	public List<Company> getAllCompany() {
		List<Company> ds = null;
			session.beginTransaction();
			Criteria cri = session.createCriteria(Company.class).add(Restrictions.eq("isActive", true));
			ds = cri.list();
			if(session!=null)
				session.close();
		return ds;
	}
	public boolean addCompany(Company company) {
		try {
			session.beginTransaction();
			session.save(company);
			session.getTransaction().commit();
			return true;
		} catch (HibernateException e) {
			if (session.getTransaction() != null) {
				session.getTransaction().rollback();
			}
			e.printStackTrace();
		} finally {
			if(session!=null)
				session.close();;
		}
		return false;
	}

	public boolean updateCompany(Company company) {
		try {
			session.beginTransaction();
			session.update(company);
			session.getTransaction().commit();
			return true;
		} catch (HibernateException e) {
			if (session.getTransaction() != null) {
				session.getTransaction().rollback();
			}
			e.printStackTrace();
		} finally {
			if(session!=null)
				session.close();
		}
		return false;
	}
	
	public Company getCompanyById(int commanyId) {
		Company company = null;
		 session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			company = (Company) session.get(Company.class, commanyId);
			session.getTransaction().commit();
			return company;
		} catch (HibernateException e) {
			if (session.getTransaction() != null) {
				session.getTransaction().rollback();
			}
			e.printStackTrace();
		} finally {
			if(session!=null)
			session.close();
		}
		return company;
	}
}
